package com.canoe;

import com.canoe.common.CanoeException;
import com.canoe.common.FirstLevelOrder;
import com.canoe.text.TextProcessor;

import java.util.ArrayList;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 一级指令适配器
 *
 * @author: btm
 * @time: 20:25 2020/9/22
 **/
public final class FirstLevelOrderAdapter {

    private static final ConcurrentHashMap<FirstLevelOrder, AbstractFirstLevelOrderProcessor> firstLevelOrderProcessorMap = new ConcurrentHashMap<>();

    private static final ArrayList<AbstractFirstLevelOrderProcessor> firstLevelOrderProcessorList = new ArrayList<>();

    static {
        firstLevelOrderProcessorList.add(new TextProcessor());
    }

    /**
     * 初始化一级指令适配器饿的时候，将所有的一级指令执行器注册到适配器中
     */
    public FirstLevelOrderAdapter() {
        if (0 >= firstLevelOrderProcessorMap.size()) {
            for (AbstractFirstLevelOrderProcessor firstLevelOrderProcessor : firstLevelOrderProcessorList) {
                if (Objects.nonNull(firstLevelOrderProcessor)) {
                    firstLevelOrderProcessorMap.put(firstLevelOrderProcessor.support(), firstLevelOrderProcessor);
                }
            }
        }
    }

    /**
     * 根据一级指令获得对应的处理器
     * @param firstLevelOrder 一级指令{@link com.canoe.common.FirstLevelOrder}
     * @return 一级指令处理器
     */
    public AbstractFirstLevelOrderProcessor getProcessor(FirstLevelOrder firstLevelOrder) {
        AbstractFirstLevelOrderProcessor processor = firstLevelOrderProcessorMap.get(firstLevelOrder);
        if (Objects.nonNull(processor)) {
            return processor;
        }
        throw new CanoeException("There is not a processor for first level order: "+firstLevelOrder.getOrderName());
    }
}
